#include<stdio.h>
#include<unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
void writer(int wfd)
{
    const char * str = "hello,Father! I am child";
    char buffer[128] ;
    int cnt =0;
    pid_t pid = getpid();
    while(1)
    {
        snprintf(buffer,sizeof(buffer),"message:%s,pid:%d,count:%d",str,pid,cnt++);
        write(wfd,buffer,strlen(buffer));
        sleep(1);
    }
}
void reader(int rfd)
{
    char buffer[1024];
    while(1)
    {
        ssize_t n =read(rfd,buffer,sizeof(buffer)-1);
        (void)n;
        printf("father get a message:%s\n",buffer);
    }

}

int main()
{
    int pipefd[2];
    int ret  = pipe(pipefd);
    if(ret == -1)
    {
        perror("fail!");
        return 1;
    }
    printf("pipefd[0] = %d\n",pipefd[0]);//reader
    printf("pipefd[1] = %d\n",pipefd[1]);//writer
    // 2.fork
    pid_t pid =fork();

    if(pid == 0)
    {
        //child:writer
        close(pipefd[0]);

        writer(pipefd[1]);
        exit(0);
    }
    //father:reader
    close(pipefd[1]);

    reader(pipefd[0]);
    wait(NULL);
    return 0;
}